//
//  LCHomeViewController.swift
//  SwiftWeiBo
//
//  Created by LiCheng on 2017/2/8.
//  Copyright © 2017年 LiCheng. All rights reserved.
//

import UIKit

// 定义全局变量，使用 private 修饰， 不然所有地方都可以调用
private let cellID = "cellID"

class LCHomeViewController: LCBaseViewController {

    /// 列表视图模型
    fileprivate lazy var listViewModel = LCStatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func loadData() {


        print("加载数据\(self.listViewModel.statusList.last?.text)")

        listViewModel.loadStatus(isPullpo: self.isPullpo) { (isSuccess, shouldRefresh) in

            // 结束刷新控件
            self.refreshControl?.endRefreshing()

            // 恢复上拉刷新标记
            self.isPullpo = false

            if shouldRefresh {
                // UI 刷新
                self.tableView?.reloadData()
            }
        }
    }


    /// 显示好友按钮
    @objc fileprivate func showFriendsClick() {

        let vc = LCMessageViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 设置界面
extension LCHomeViewController {

    /// 重写 父类方法 设置 UI
    override func setupTableView() {
        super.setupTableView()

        // 设置 导航栏左按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriendsClick))

        // 注册 cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellID)

        setupNavTitle()
    }

    /// 设置导航栏标题视图
    private func setupNavTitle() {

        let title = LCNetworkManager.shared.userAccount.screen_name

        let button = LCTitleButton(title: title)

        navItem.titleView = button

        button.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
    }

    /// 标题视图点击事件
    @objc private func titleBtnClick(btn: UIButton) {
        // 切换选中状态
        btn.isSelected = !btn.isSelected
    }

}

// MARK: - tableView 数据源方法
extension LCHomeViewController {

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // 1. 获取 cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)

        // 2. 设置 cell
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text

        // 3. 返回 cell
        return cell
    }
}
